package com.jeesite.modules.financial.service.bydconfig;

import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.service.CrudService;
import com.jeesite.common.utils.SpringUtils;
import com.jeesite.common.web.http.HttpClientUtils;
import com.jeesite.common.web.http.SapResponseEntity;
import com.jeesite.modules.financial.dao.bydconfig.TbydConfigDao;
import com.jeesite.modules.financial.entity.bydconfig.ItemDemo;
import com.jeesite.modules.financial.entity.bydconfig.TbydConfig;
import com.jeesite.modules.sys.entity.Log;
import com.jeesite.modules.sys.service.LogService;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class BydDayCreditService extends CrudService<TbydConfigDao, TbydConfig> {

    private Logger logger = Logger.getLogger(BydDayCreditService.class);

    @Autowired
    private TbydConfigDao tbydConfigDao;

    public void dayCredit(List<Map<String,Object>> mapList){
        //获取Byd日记账信息
        String bydCode = TbydTypeCode.BYD_RJZ.getCode();
        TbydConfig tbydConfig = super.get(bydCode);
        String bydHost = tbydConfig.getBydHost();
        String bydAuth = tbydConfig.getBydAuthorization();
        String bydUserName = tbydConfig.getBydUsername();
        String bydPassword = tbydConfig.getBydPassword();
        String bydCompanyId = tbydConfig.getBydCompanyId();
        String bydSystemId = tbydConfig.getBydSystemId();
        String bydTypeCode = tbydConfig.getBydTypeCode();

        String bydHeaderId = null;
        String originalEntryDocumentReferenceID = null;
        String transactionDate = null;
        List<ItemDemo> itemDemos = null;
        String requestContent = null;
        String responseResult = null;
        String uuid = null;
        LogService logService = SpringUtils.getBean(LogService.class);
        for (Map<String,Object> map:mapList) {
            bydHeaderId = String.valueOf(map.get("bydHeaderId"));
            originalEntryDocumentReferenceID = String.valueOf(map.get("originalEntryDocumentReferenceID"));
            transactionDate = String.valueOf(map.get("transactionDate"));
            itemDemos = (List<ItemDemo>) map.get("itemDemos");
            requestContent = createRequestContent(bydHeaderId,originalEntryDocumentReferenceID,transactionDate,bydCompanyId,bydSystemId,bydTypeCode,itemDemos);
            SapResponseEntity sapResponseEntity = HttpClientUtils.sapMessage(requestContent,bydHost,bydAuth,bydUserName,bydPassword);
            responseResult = sapResponseEntity.getUuidResult();
            //获取uuid标签之间的uuid值
            uuid = getUUidByResult(responseResult);
            if(StringUtils.isNotEmpty(uuid)){
                //回填各个表uuid字段
            }
            //保存日志相关信息到日志表
            insertLog(logService,requestContent,responseResult,uuid);
            //如果是超时失败,给予重试机会
            if(StringUtils.isBlank(uuid)&&sapResponseEntity.isReFlag()){
                SapResponseEntity sapResponseEntityNew = HttpClientUtils.sapMessage(requestContent,bydHost,bydAuth,bydUserName,bydPassword);
                responseResult = sapResponseEntityNew.getUuidResult();
                uuid =  getUUidByResult(responseResult);
                if(StringUtils.isNotEmpty(uuid)){
                    //回填各个表uuid字段
                }
                //保存日志相关信息到日志表
                insertLog(logService,requestContent,responseResult,uuid);
            }
        }
    }

    public String createRequestContent(String bydHeaderId, String originalEntryDocumentReferenceID, String transactionDate, String bydCompanyId,String bydSystemId,String bydTypeCode, List<ItemDemo> itemDemos){
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:glob=\"http://sap.com/xi/SAPGlobal20/Global\">");
        stringBuffer.append("<soapenv:Header/>");
        stringBuffer.append("<soapenv:Body>");
        stringBuffer.append("<n0:JournalEntryBundleCreateRequest xmlns:n0=\"http://sap.com/xi/SAPGlobal20/Global\">");
        stringBuffer.append("<BasicMessageHeader>");
        stringBuffer.append("<ID>");
        stringBuffer.append(bydHeaderId);
        stringBuffer.append("</ID>");
        stringBuffer.append("</BasicMessageHeader>");
        stringBuffer.append("<JournalEntry>");
        stringBuffer.append("<ObjectNodeSenderTechnicalID>1</ObjectNodeSenderTechnicalID>");
        stringBuffer.append("<CompanyID>");
        stringBuffer.append(bydCompanyId);
        stringBuffer.append("</CompanyID>");
        stringBuffer.append("<OriginalEntryDocumentReferenceID>");
        stringBuffer.append(originalEntryDocumentReferenceID);
        stringBuffer.append("</OriginalEntryDocumentReferenceID>");
        stringBuffer.append("<OriginalEntryDocumentReferenceBusinessSystemID>");
        stringBuffer.append(bydSystemId);
        stringBuffer.append("</OriginalEntryDocumentReferenceBusinessSystemID>");
        stringBuffer.append("<AccountingBusinessTransactionDate>");
        stringBuffer.append(transactionDate);
        stringBuffer.append("</AccountingBusinessTransactionDate>");
        stringBuffer.append("<AccountingBusinessTransactionTypeCode>");
        stringBuffer.append(bydTypeCode);
        stringBuffer.append("</AccountingBusinessTransactionTypeCode>");

        for(int i=0;i<itemDemos.size();i++) {
            stringBuffer.append("<Item>");
            stringBuffer.append("<ObjectNodeSenderTechnicalID>");
            stringBuffer.append(2+i);
            stringBuffer.append("</ObjectNodeSenderTechnicalID>");
            stringBuffer.append("<OriginalEntryDocumentItemReferenceItemID>");
            stringBuffer.append(1+i);
            stringBuffer.append("</OriginalEntryDocumentItemReferenceItemID>");
            stringBuffer.append("<GeneralLedgerAccountAliasCode>");
            stringBuffer.append(itemDemos.get(i).getGeneralLedgerAccountAliasCode());
            stringBuffer.append("</GeneralLedgerAccountAliasCode>");
            stringBuffer.append("<BusinessTransactionCurrencyAmount currencyCode=\"");
            stringBuffer.append(itemDemos.get(i).getCurrencyCode());
            stringBuffer.append("\">");
            stringBuffer.append(itemDemos.get(i).getBusinessTransactionCurrencyAmount().doubleValue());
            stringBuffer.append("</BusinessTransactionCurrencyAmount>");
            stringBuffer.append("<Node>");
            stringBuffer.append(itemDemos.get(i).getNode());
            stringBuffer.append("</Node>");
            stringBuffer.append("</Item>");
        }

        stringBuffer.append("</JournalEntry>");
        stringBuffer.append("</n0:JournalEntryBundleCreateRequest>");
        stringBuffer.append("</soapenv:Body>");
        stringBuffer.append("</soapenv:Envelope>");
        return stringBuffer.toString();
    }

    public String getUUidByResult(String uuidResult){
        Pattern p = Pattern.compile("<UUID>(.*)</UUID>");
        Matcher m = p.matcher(uuidResult);
        while(m.find()){
           return m.group(1);
        }
        return null;
    }

    public void insertLog(LogService logService,String requestContent,String responseResult,String uuid){
        Log log = new Log();
        //必须字段
        log.setLogType("byd");
        log.setLogTitle("byd");
        log.setCreateBy("system");
        log.setCreateByName("system");
        log.setCreateDate(new Date());
        log.setRemoteAddr("SAP");
        log.setServerAddr("local");
        log.setBizKey("bydCredit");
        log.setBizType("byd");
        log.setIsException("0");
        log.setCorpCode("JeeSite");
        log.setCorpName("JeeSite");
        //具体信息
        log.setRequestContent(requestContent);
        logger.info("--------------------------------------------------");
        logger.info(requestContent);
        logger.info("--------------------------------------------------");
        log.setResponseContent(responseResult);
        logger.info("--------------------------------------------------");
        logger.info(responseResult);
        logger.info("--------------------------------------------------");
        //recordStatus:0失败1成功
        if(StringUtils.isNotEmpty(uuid)){
            log.setRecordStatus("1");
        }else{
            log.setRecordStatus("0");
        }
        log.setIsNewRecord(true);
        logService.insertLog(log);
    }
}
